package com.chtw.oasystem.controller;

import com.chtw.oasystem.common.response.RespUtils;
import com.chtw.oasystem.respBean.ListTrainResp;
import com.chtw.oasystem.respBean.TrainResp;
import com.chtw.oasystem.service.impl.TrainServiceImpl;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author chenhao03
 * @create 2020-11-21 14:08
 */
@RestController
@ResponseBody
@RequestMapping("/train")
public class TrainController {
    private static final Logger logger = LoggerFactory.getLogger(TrainController.class);

    @Autowired
    private TrainServiceImpl trainService;

    @GetMapping("/list")
    public RespUtils<ListTrainResp> list(@RequestParam(defaultValue = "1", required = false) int page, @RequestParam(defaultValue = "10", required = false) int limit, String search) {
        try {
            PageInfo<TrainResp> info = trainService.list(search, page, limit);
            return RespUtils.success(new ListTrainResp((int) info.getTotal(), info.getPages(), info.getList()));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return RespUtils.fail(e.getMessage());
        }
    }

    @GetMapping("/info")
    public RespUtils<TrainResp> info(int id) {
        try {
            return RespUtils.success(trainService.info(id));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return RespUtils.fail(e.getMessage());
        }
    }

    @PostMapping("/create")
    public RespUtils<Boolean> create(HttpSession session, @RequestBody TrainResp train) {
        try {
            return RespUtils.success(trainService.create(session, train));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return RespUtils.fail(e.getMessage());
        }
    }

    @PostMapping("/edit")
    public RespUtils<Boolean> edit(HttpSession session, @RequestBody TrainResp train) {
        try {
            return RespUtils.success(trainService.edit(session, train));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return RespUtils.fail(e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    public RespUtils<Boolean> delete(HttpSession session, @RequestBody int id) {
        try {
            return RespUtils.success(trainService.delete(session, id));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return RespUtils.fail(e.getMessage());
        }
    }
}
